package com.example.wangli.caterapp.util;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 公共连接操作,在登录成功后给sessionId赋值，此后请求都会用同一个sessionId,因为登录成功的sessionId里缓存了登录信息
 * @author wangli
 *
 */
public  class ClientConnect {
    private static String sessionId;
    private static ObjectMapper mapper = new ObjectMapper();
    /**
     * post方式请求,将参数封装在对象里
     * @param url
     * @param object
     * @return
     * @throws Exception
     */
    public static HttpURLConnection doPost (String url,Object object) throws Exception{

        URL urL = UrlFactory.getUrlInstance(url);
        HttpURLConnection con = (HttpURLConnection)urL.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Cookie", sessionId);
        con.setRequestProperty("Content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.connect();

        //请求体里放数据
        DataOutputStream data = new DataOutputStream(con.getOutputStream());
        String line = mapper.writeValueAsString(object);
        System.out.println(line);
        data.write(line.getBytes());
        data.close();

        return con;
    }
    /**
     * get方式请求,将参数拼接在url后
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public static HttpURLConnection doGet(String url,String str) throws Exception{
        URL urL = UrlFactory.getUrlInstance(url+"?"+str);
        HttpURLConnection con = (HttpURLConnection)urL.openConnection();

        con.setRequestMethod("GET");
        con.setRequestProperty("Cookie", sessionId);
        con.setDoOutput(true);
        con.setDoInput(true);


        return con;
    }

}
